<?php

namespace App\Http\Middleware;

use App\Repositories\OperationLogRepository;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class OperationLogMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);
        if (auth('admin')->check() && $request->is('admin/*')) {
            app(OperationLogRepository::class)->create([
                'admin_id' => auth('admin')->user()->id,
                'name' => auth('admin')->user()->name,
                'ip' => $request->ip(),
                'method' => $request->method(),
                'url' => $request->fullUrl(),
                'params' => json_encode($request->all()),
                'user_agent' => $request->header('user-agent'),
                'response' => json_encode($response->getContent()),
                'status_code' => $response->getStatusCode(),
                // 单位毫秒
                'duration' => (microtime(true) - LARAVEL_START) * 1000,
            ]);
        }
        return $response;
    }
}
